package com.youdianstar.app.common.network

import android.view.View
import androidx.lifecycle.Observer
import com.google.gson.JsonParseException
import com.youdianstar.app.common.loadsir.ErrorCallback
import com.youdianstar.app.common.loadsir.LoadingCallback
import com.youdianstar.app.common.network.model.BaseResponse
import com.youdianstar.app.common.network.model.DataState

import com.kingja.loadsir.callback.Callback
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.Convertor
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.youdianstar.app.common.loadsir.EmptyCallback
import com.youdianstar.app.common.loadsir.EmptyInviteRcCallback
import com.youdianstar.app.common.loadsir.EmptyRecordCallback
import com.youdianstar.app.common.util.LogUtil
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.text.ParseException


/**
 * File: BaseApiListStateObserver
 * Author: 82149 Create: 2021/11/1 17:11
 * Changes (from 2021/11/1)
 * --------------------------------------------------
 * description: 接口数据回调 --更改UI(列表)
 * ---------------------------------------------------
 *
 */
private const val TAG = "BaseApiLsStateObserver"

abstract class BaseApiLsStateObserver<T>(view: View,autoNet: Boolean) : Observer<BaseResponse<T>>, Callback.OnReloadListener{
    private var mLoadService: LoadService<DataState>
    private var isAutoUpdate = true
    init {
        //LoadSir 针对单个View 做注册
        mLoadService = LoadSir.getDefault().register(view, this, Convertor<DataState> { t ->
            var resultCall: Class<out Callback> = SuccessCallback::class.java
            t.let { state ->
                when (state) {
                    //数据刚开始请求，loading
                    DataState.STATE_CREATE, DataState.STATE_LOADING -> {
                        resultCall = LoadingCallback::class.java
                    }
                    //请求成功
                    DataState.STATE_SUCCESS -> resultCall = SuccessCallback::class.java
                    //数据为空
                    DataState.STATE_EMPTY -> resultCall = EmptyCallback::class.java
                    DataState.STATE_EMPTY_RC -> resultCall = EmptyRecordCallback::class.java
                    DataState.STATE_EMPTY_IN -> resultCall = EmptyInviteRcCallback::class.java
                    //加载失败
                    DataState.STATE_FAILED, DataState.STATE_ERROR -> {
                        resultCall = ErrorCallback::class.java
                    }
                    DataState.STATE_COMPLETED, DataState.STATE_UNKNOWN -> {
                        //非普通异常,默认给成功吧
                        resultCall = SuccessCallback::class.java
                    }
                    else -> {}
                }
            }
            resultCall
        }) as LoadService<DataState>

        isAutoUpdate = autoNet
    }

    private fun handleError(t: BaseResponse<T>) {
        when (val error: Throwable? = t.error) {
            is HttpException -> {
                //网络错误
                LogUtil.e(TAG, "----HttpException:" + error.message())
            }
            is ConnectException -> {
                //无网络连接
                LogUtil.e(TAG, "----ConnectException:" + error.message)
            }
            is InterruptedIOException -> {
                //连接超时
                LogUtil.e(TAG, "----InterruptedIOException:" + error.message)
            }
            is JsonParseException, is JSONException, is ParseException -> {
                //解析错误
                LogUtil.e(TAG, "----JsonEx:" + error.message)
            }
            else -> {
                //未知错误
                LogUtil.e(TAG, "----Unknown Http Exception:" + error?.message)
            }
        }
    }

    /*数据处理*/
    override fun onChanged(t: BaseResponse<T>) {
//        Log.d(TAG, "onChanged: ${t.dataState}")
        when (t.dataState) {
            DataState.STATE_SUCCESS -> {
                onDataResult(t.data)
            }

            DataState.STATE_EMPTY -> {
                onDataEmpty()
            }

            DataState.STATE_FAILED ->{
                // 优先使用 message，如果没有则使用 error 的 message
                val errorMsg = t.message ?: t.error?.message ?: "Request failed"
                onNetError(t.code, errorMsg)
            }
            DataState.STATE_ERROR -> {
                //请求错误
                handleError(t)
                // 优先使用 message，如果没有则使用 error 的 message
                val errorMsg = t.message ?: t.error?.message ?: "Network error occurred"
                onNetError(-1, errorMsg)
            }
            else -> {
            }
        }
        //处理UI :转换器回调
        if (isAutoUpdate)
            mLoadService.showWithConvertor(t.dataState)
    }

    /**
     * 请求数据且数据不为空
     */
    abstract fun onDataResult(data: T?)

    /**
     * 请求成功，但数据为空
     */
    open fun onDataEmpty() {}

    /**
     * 请求错误
     */
    open fun onNetError(code: Int, e: String?) {}

    /**
     * 外部回调更新
     * @param state DataState.STATE_SUCCESS
     */
    fun showViewState(state: DataState) {
        mLoadService.showWithConvertor(state)
    }

}